import 'dart:async';

import 'package:get/get.dart';
import 'package:sinosheets/utils/language/language_util.dart';
import 'package:intl/intl.dart';

class GBTimeUtils {
  /// 解析时间字符串：
  /// 1. 如果带时区则直接解析并转换为本地时区
  /// 2. 如果不带时区，则按北京时间（UTC+8）解析后转换为本地时区
  static DateTime parseTime(String timeString) {
    if (timeString.isEmpty) {
      return DateTime.now();
    }
    // LogUtil.e('timeString: $timeString');
    try {
      // 检查是否包含时区信息
      bool hasTimeZone = timeString.contains('Z') ||
          // 检查是否包含时区偏移格式（如 +08:00 或 -08:00）
          RegExp(r'[+-]\d{2}:?\d{2}$').hasMatch(timeString);

      DateTime dateTime;
      if (hasTimeZone) {
        // 有时区信息，直接解析
        dateTime = DateTime.parse(timeString);
      } else {
        // 无时区信息，直接按本地时间解析
        dateTime = DateTime.parse('${timeString}+08:00');
      }
      return dateTime.toLocal();
    } catch (e) {
      // 解析失败时返回当前时间
      // LogUtil.e('时间解析失败: $timeString');
      return DateTime.now();
    }
  }

  /// 将 UTC 时间字符串转换为本地时间字符串（带人性化格式）
  static String utcToLocal(String utcTime, {String format = 'yyyy-MM-dd HH:mm'}) {
    try {
      DateTime utcDateTime = parseTime(utcTime);
      DateTime localDateTime = utcDateTime.toLocal();
      DateTime now = DateTime.now();

      Duration difference = now.difference(localDateTime);
      if (difference.inMinutes < 60) {
        return difference.inMinutes < 1 ? 'just_now'.tr : '${difference.inMinutes} ${'minutes_ago'.tr}';
      } else if (now.year == localDateTime.year && now.month == localDateTime.month && now.day == localDateTime.day) {
        return '${'today'.tr} ${DateFormat('HH:mm').format(localDateTime)}';
      } else if (difference.inDays == 1) {
        return '${'yesterday'.tr} ${DateFormat('HH:mm').format(localDateTime)}';
      } else {
        return DateFormat(format).format(localDateTime);
      }
    } catch (e) {
      return 'Invalid Date';
    }
  }

  /// 普通 UTC 字符串转本地时间
  static String utcStringToLocal(String utcString, {String format = "yyyy-MM-dd HH:mm:ss"}) {
    if (utcString.isEmpty) {
      return '';
    }
    DateTime localDateTime = parseTime(utcString);
    return DateFormat(format).format(localDateTime);
  }

  /// 获取当前时间的 UTC 格式
  static String getCurrentUtcTime({String format = "yyyy-MM-dd'T'HH:mm:ss'Z'"}) {
    return DateFormat(format).format(DateTime.now().toUtc());
  }

  /// 获取当前时间的本地格式
  static String getCurrentLocalTime({String format = 'yyyy-MM-dd HH:mm'}) {
    return DateFormat(format).format(DateTime.now());
  }

  /// 时间相加
  static String getExpireTime(String time, int days, {int hours = 0, int minutes = 0, int seconds = 0}) {
    DateTime? dateTime = DateTime.tryParse(time);
    if (dateTime == null) {
      return "";
    }
    dateTime = dateTime.add(Duration(days: days, hours: hours, minutes: minutes, seconds: seconds));
    String expireTime = DateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(dateTime);
    return expireTime;
  }

  /// 判断是否过期
  static bool isExpire(String expireTimeString) {
    return parseTime(expireTimeString).isBefore(DateTime.now());
  }

  /// 判断是否在活动期间
  static bool isActive(String startTimeString, String endTimeString) {
    return isExpire(startTimeString) && !isExpire(endTimeString);
  }

  /// 获取倒计时剩余时间
  static Map<String, dynamic> getRemainingTime(
    String expireTimeString, {
    bool withSecond = true,
  }) {
    DateTime expireTime = parseTime(expireTimeString);
    DateTime now = DateTime.now();

    // 将两个时间都转换为UTC时间进行比较
    DateTime expireTimeUtc = expireTime.toUtc();
    DateTime nowUtc = now.toUtc();
    Duration remaining = expireTimeUtc.difference(nowUtc);

    if (remaining.isNegative) return {};
    if (expireTimeUtc.isAtSameMomentAs(nowUtc)) return {};

    int days = remaining.inDays;
    int hours = remaining.inHours % 24;
    int minutes = remaining.inMinutes % 60;
    int seconds = remaining.inSeconds % 60;

    String hoursString = hours.toString().padLeft(2, '0');
    String minutesString = minutes.toString().padLeft(2, '0');
    String secondsString = seconds.toString().padLeft(2, '0');

    String timeString = "";
    if (days > 0) {
      timeString += '$days${"day".tr}';
    }
    if (hours > 0) {
      timeString += '$hours${"hour".tr}';
    }
    if (minutes > 0) {
      timeString += '$minutes${"minute".tr}';
    }
    if (withSecond && seconds > 0) {
      timeString += '$seconds${"second".tr}';
    }

    String showTime = days > 0 ? (LanguageUtil.isChinese() ? '$days天$hours小时' : '${days}d ${hours}h') : '$hoursString:$minutesString${withSecond ? ":$secondsString" : ""}';

    String downTime = "${remaining.inHours}:$minutesString";
    if (withSecond) downTime += ":$secondsString";

    return {
      'days': days,
      'hours': hours,
      'minutes': minutes,
      'seconds': seconds,
      'timeString': timeString,
      'showTime': showTime,
      "downTime": downTime,
    };
  }
}

class GBCountdownTimer {
  final String expireTime;
  Timer? _timer;

  GBCountdownTimer(this.expireTime);

  // 计算剩余时间
  Duration _getRemainingDuration() {
    DateTime expireTime = GBTimeUtils.parseTime(this.expireTime);
    DateTime now = DateTime.now();
    return expireTime.difference(now);
  }

  // 获取倒计时剩余时间
  Map<String, dynamic> getRemainingTime() {
    Duration remaining = _getRemainingDuration();

    if (remaining.isNegative) return {};

    int days = remaining.inHours ~/ 24; // 使用整除计算天数
    int hours = remaining.inHours % 24; // 剩余小时数
    int minutes = remaining.inMinutes % 60;
    int seconds = remaining.inSeconds % 60;

    String hoursString = hours.toString().padLeft(2, '0');
    String minutesString = minutes.toString().padLeft(2, '0');
    String secondsString = seconds.toString().padLeft(2, '0');

    String timeString = '$days${"day".tr}$hoursString${"hour".tr}$minutesString${"minute".tr}$secondsString${"second".tr}';

    String showTime = days > 0 ? (LanguageUtil.isChinese() ? '$days天$hours小时' : '${days}d${hours}h') : '$hoursString:$minutesString:$secondsString';

    String downTime = "${remaining.inHours}:$minutesString:$secondsString";

    return {
      'days': days,
      'hours': hours,
      'minutes': minutes,
      'seconds': seconds,
      'timeString': timeString,
      'showTime': showTime,
      "downTime": downTime,
    };
  }

  // 开始倒计时
  void startCountdown(Function(Map<String, dynamic>) onUpdate) {
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      Map<String, dynamic> time = getRemainingTime();
      onUpdate(time);
      if (_getRemainingDuration().inSeconds <= 0) {
        stopCountdown();
      }
    });
  }

  // 停止倒计时
  void stopCountdown() {
    _timer?.cancel();
    _timer = null;
  }

  // 判断倒计时是否结束
  bool isTimeUp() {
    return _getRemainingDuration().isNegative;
  }
}
